import { throttle } from 'lodash-es';
import {
    NavigationMenu,
    NavigationMenuItem,
    NavigationMenuList
} from "@/components/ui/navigation-menu";
import {
    Sheet,
    SheetContent,
    SheetHeader,
    SheetTrigger, SheetTitle, SheetDescription
} from "@/components/ui/sheet"
import { Input } from "@/components/ui/input";
import routes from "@/routes/index.tsx";
import { useEffect, useState, useRef, useCallback } from "react";
import { Menu } from "lucide-react";
import { ThemeToggle } from "@/components/ThemeToggle";
import { motion } from 'framer-motion';
import { NavLink, useLocation } from 'react-router-dom';

function NavBar() {
    const location = useLocation();
    const menuRef = useRef<HTMLDivElement>(null);
    const [activePath, setActivePath] = useState("");
    const [lastScrollY, setLastScrollY] = useState(0);
    const [searchQuery, setSearchQuery] = useState('');
    const [isScrolled, setIsScrolled] = useState(false);
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [isNavVisible, setIsNavVisible] = useState(true);

    // 节流处理函数
    const handleScroll = useCallback(throttle(() => {
        const currentScrollY = window.scrollY;
        // 菜单打开时禁用隐藏逻辑
        if (!isMenuOpen) {
            if (currentScrollY > lastScrollY && currentScrollY > 100) {
                setIsNavVisible(false);
            } else if (currentScrollY < lastScrollY || currentScrollY < 60) {
                setIsNavVisible(true);
            }
        }

        setIsScrolled(currentScrollY > 60);
        setLastScrollY(currentScrollY);
    }, 200), [lastScrollY, isMenuOpen]);

    useEffect(() => {
        setActivePath(location.pathname);
    }, [location]);

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, [handleScroll]);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
                setIsMenuOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    // 渲染导航项
    const renderNavItems = (isMobile = false) => (
        routes.map((route) =>
            route.children?.map((child: {
                path: string;
                isShow: boolean;
                meta?: {
                    title: string;
                    isIcon?: boolean;
                }
            }) => (
                // 根据isShow属性判断是否渲染
                child.isShow && (
                    <NavigationMenuItem
                        key={child.path}
                        className={`p-2 list-none flex justify-items-center transition-colors ${activePath === child.path
                            ? "text-themeEnglishLight dark:text-themeEnglishDark font-semibold"
                            : "hover:text-themeEnglishLight dark:hover:text-themeEnglishDark duration-300"
                            }`}
                    >
                        <NavLink
                            to={child.path}
                            onClick={() => {
                                setIsMenuOpen(false);
                                document.body.style.overflow = "auto";
                            }}
                            className={`flex ${isMobile ? "w-full text-center py-3" : ""}`}
                        >
                            {child.meta?.title}
                        </NavLink>
                    </NavigationMenuItem>
                )
            ))
        )
    );

    return (
        <nav
            ref={menuRef}
            className={`w-full flex flex-wrap items-center justify-between h-16 z-50 p-3 fixed top-0 bg-white/80 dark:bg-bigDarkArea/80 backdrop-blur-sm shadow-sm
            transition-transform duration-500 ease-in-out ${isNavVisible ? 'translate-y-0' : '-translate-y-full'
                } ${isScrolled ? 'shadow-lg' : 'shadow-none'
                }`}
            style={{
                zIndex: 9,
                // 兼容Safari的backdrop-filter
                backdropFilter: 'blur(12px)',
                WebkitBackdropFilter: 'blur(12px)'
            }}
        >
            {/* Logo 淡入动画 */}
            <motion.div
                initial={{ opacity: 0, x: -50 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.8, delay: 0.2 }}
                className="flex items-center justify-between w-full md:w-auto relative h-full md:flex-1"
            >
                <NavLink to="/" className="z-10 hover:brightness-110 transition-all md:flex-1">
                    <span className="font-code text-3xl text-englishLight dark:text-englishDark">MK</span>
                </NavLink>
                {/* 桌面导航菜单 */}
                <motion.div
                    initial={{ opacity: 0, y: -50 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.8, delay: 0.4 }}
                    className="hidden md:block md:flex-1"
                >
                    <NavigationMenu>
                        <NavigationMenuList className="gap-4">
                            {renderNavItems()}
                        </NavigationMenuList>
                    </NavigationMenu>
                </motion.div>
                <div className="relative md:right-[40px]">
                    <Input
                        type="text"
                        placeholder="按下回车搜索"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                                // 清空搜索框
                                setSearchQuery('');
                            }
                        }}
                        className="bg-smallLightArea/50 dark:bg-smallDarkArea border-gray-700 text-gray-200 placeholder-gray-500"
                        style={{
                            outline: '0'
                        }}
                    />
                </div>
                {/* 移动端 控制栏 */}
                <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ duration: 0.6, delay: 0.1 }}
                    className="md:hidden"
                >
                    <Sheet key={"left"}>
                        <SheetTrigger onClick={() => setIsMenuOpen(!isMenuOpen)}>
                            <Menu className={`transition-all`} />
                        </SheetTrigger>
                        <SheetContent side={"left"} className="pt-20" onOpenAutoFocus={(e) => e.preventDefault()}>
                            <SheetHeader>
                                <SheetTitle>
                                    菜单
                                </SheetTitle>
                                <SheetDescription>
                                    Make changes to your profile here. Click save when you're done.
                                </SheetDescription>
                                {renderNavItems(true)}
                            </SheetHeader>
                            <ThemeToggle />
                        </SheetContent>
                    </Sheet>
                </motion.div>
            </motion.div>



            {/* Web端 主题切换 */}
            <motion.div
                initial={{ opacity: 0, x: 50 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.8, delay: 0.2 }}
                className="hidden md:block"
            >
                <ThemeToggle />
            </motion.div>
        </nav>
    );
}

export default NavBar;